package io.seata.samples.integration.storage.service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.seata.core.context.RootContext;
import io.seata.samples.integration.common.dto.AccountDTO;
import io.seata.samples.integration.common.dto.CommodityDTO;
import io.seata.samples.integration.common.dubbo.AccountDubboService;
import io.seata.samples.integration.common.enums.RspStatusEnum;
import io.seata.samples.integration.common.response.ObjectResponse;
import io.seata.samples.integration.storage.entity.TStorage;
import io.seata.samples.integration.storage.mapper.TStorageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  库存服务实现类
 * </p>
 *
 * @author wwg
 */
@Service
public class TStorageServiceImpl extends ServiceImpl<TStorageMapper, TStorage> implements ITStorageService {

    @Reference(version = "1.0.0",check = false)
    private AccountDubboService accountDubboService;

    /**
     * 单独的减库存 和 扣减账户 只需要通过本地spring 事务来实现即可
     * @param commodityDTO
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ObjectResponse decreaseStorage(CommodityDTO commodityDTO) throws Exception {

        System.out.println("全局事务id ：" + RootContext.getXID());

        int storage = baseMapper.decreaseStorage(commodityDTO.getCommodityCode(), commodityDTO.getCount());

        if (storage == 0) {
            throw new Exception("decrease storage fail !!!");
        }
        //扣减用户账户
        AccountDTO accountDTO = new AccountDTO();
        accountDTO.setUserId(commodityDTO.getUserId());
        accountDTO.setAmount(commodityDTO.getAmount());
        ObjectResponse objectResponse = accountDubboService.decreaseAccount(accountDTO);

        ObjectResponse<Object> response = new ObjectResponse<>();
        if (storage > 0 && RspStatusEnum.SUCCESS.getCode() == objectResponse.getStatus()){
            response.setStatus(RspStatusEnum.SUCCESS.getCode());
            response.setMessage(RspStatusEnum.SUCCESS.getMessage());
            return response;
        }

        throw new Exception(RspStatusEnum.FAIL.getMessage());
//        response.setStatus(RspStatusEnum.FAIL.getCode());
//        response.setMessage(RspStatusEnum.FAIL.getMessage());
//        return response;
    }
}
